'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 清除CD
 * @author agl
 */

var _ = require('lodash');
var async = require('async');
var moment = require('moment');
var Code = require('../../../../consts/code');
var moduleType = require('../../../../consts/moduleType');
var operationType = require('../../../../consts/operationType');
var configUtil = require('../../../../util/configUtil');
var PlayerManager = require('../../../../libs/playerManager');
var taskService = require('../../../../services/taskService');
var roleService = require('../../../../services/roleService');
var buildService = require('../../../../services/buildService');
var dataApi = require('../../../../libs/dataApi.js');

module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var carbon_type = msg.carbon_type;

    if (!carbon_type) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var model_name;
    if (carbon_type === 1) {
        model_name = 'gold_carbon';
    } else {
        model_name = 'food_carbon';
    }

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    [model_name, 'role', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var act_carbon_model = player_manager[model_name];
                var now_tm = moment().unix();
                var cd_length = act_carbon_model.freeze_tm - now_tm;
                if (cd_length <= 0) {
                    return next(null, {
                        code: Code.OK
                    });
                }

                var need_diamond = buildService.getDirectProduceDiamond(cd_length);
                if (!roleService.subDiamond(player_manager, moduleType.MDL_ACT_CARBON, operationType.OPR_ACT_CARBON_CLEAR_CD, need_diamond)) {
                    // 钻石够不够
                    return next(null, {
                        code: Code.USER_DIAMOND_NOT_ENOUGH
                    });
                }
                act_carbon_model.freeze_tm = now_tm;

                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }

            return next(null, {
                code: Code.OK
            });
        }
    );
};
